package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    @Transactional
    //撤销申请
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断审核状态，不是审核中的数据不能撤销
        if (!carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            throw new BusinessException("非法操作");
        }
        //将CarPackageAudit的状态修改为撤销审核
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
        //将服务单项的审核状态改为初始化
        serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        //删除对应的流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"删除");
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断状态，若状态是审核中，则获取其高亮节点的集合，否则返回一个空集合
        List<String> list = new ArrayList<>();
        if (carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            list = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        } else {
            list = Collections.emptyList();
        }
        //走的节点进行高亮显示
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmninfoId());
        InputStream inputStream = generator.generateDiagram(repositoryService.getBpmnModel(bpmnInfo.getActProcessId()), list, Collections.emptyList(),
                "宋体", "宋体", "宋体");
        //调用那个工具类生成
        return inputStream;
    }

    @Override
    //审核操作
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //根据id获取carpackageAudit
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断其状态是否为审核中，不是抛出异常
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw  new BusinessException("非法操作");
        }
        //获取其任务节点,设置流程变量，设置审核状态
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        HashMap<String, Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        //审批任务
        taskService.complete(task.getId(),map);
        //判断auditStatus                            是同意（2）还是拒绝（1）
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            //同意
            //获取任务节点，为空，则修改CarPackageAudit设置审批时间，修改审批状态为审核通过，添加备注   &&  修改单项任务的状态为审核通过
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask==null) {
                serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            } else {
                //有下一个任务节点，CarPackageAudit设置任务节点的审核人，更新数据，更新时间
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }
            carPackageAudit.setInfo(carPackageAudit.getInfo() +"-----> [审核人:"+ShiroUtils.getUser().getUserName()+"]--同意--备注:"+info);
        } else if(CarPackageAudit.STATUS_REJECT.equals(auditStatus)){
            //拒绝，修改CarPackageAudit设置审批时间，修改审批状态为重新调整，添加备注
            //修改单项任务的状态为初始化
            serviceItemMapper.changeStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAudit.setInfo(carPackageAudit.getInfo() +"-----> [审核人:"+ShiroUtils.getUser().getUserName()+"]--不同意--备注:"+info);
        }
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }


}
